package org.example.interceptor;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.shardingsphere.infra.hint.HintManager;
import org.example.threadlocal.UserContext;
import org.springframework.util.StringUtils;

import java.sql.Connection;
import java.util.List;
import java.util.Properties;

@Intercepts({
        @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class TableNameInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object target = invocation.getTarget();
        if ((target instanceof StatementHandler)) {
            StatementHandler statementHandler = (StatementHandler) target;
            MetaObject metaObject = SystemMetaObject.forObject(statementHandler);

            // 获取MappedStatement
            MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");

            // 获取BoundSql
            BoundSql boundSql = statementHandler.getBoundSql();

            // 获取SQL语句
            String sql = boundSql.getSql();
            String modifiedSql = sql;

            // 替换表名
            String user = UserContext.getUser();
            if (StringUtils.hasText(user) && user.equals("sharding")) {
                modifiedSql = sql.replace("jk_customer", "sharding_jk_customer");
            }

            // 设置修改后的SQL语句
            metaObject.setValue("delegate.boundSql.sql", modifiedSql);

            //强制只查course_1表
//            HintManager hintManager = HintManager.getInstance();
            //注意这两个属性，dataSourceBaseShardingValue用于强制分库
            // 强制查course_1表
//        hintManager.setDatabaseShardingValue(1L);
//            hintManager.addTableShardingValue("jk_customer_2025", "1");
        }
        //线程安全，所有用完要注意关闭。
        //hintManager关闭的主要作用是清除ThreadLocal，释放内存。HintManager实现了AutoCloseable接口，所以建议使用try-resource的方式，用完自动关闭。
        //try(HintManager hintManager = HintManager.getInstance()){ xxxx }
        Object proceed = invocation.proceed();
//        hintManager.close();

        return proceed;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // 可以设置一些属性
    }
}
